package net.chrisrichardson.ec2deployer.cluster

import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.core.EC2
import net.chrisrichardson.ec2deployer.core.CloudManager

class SingleInstanceTopology implements ClusterTopology {

    ClusterHosts allocateServers(CloudManager ec2, ClusterSpec spec, reuseRunningInstances) {
        def extraParams = [:]
        if (spec.ebsVolume?.useExistingVolume) {
            extraParams = ["Placement.AvailabilityZone" : ec2.getAvailabilityZoneOfEbsVolume(spec.ebsVolume)]
        }
        List<EC2Server> mainServers = ec2.newServers(1, spec.tomcatInstanceType, extraParams)
        return new ClusterHosts(databaseServer: mainServers[0],
                mySqlSlaves: allocateMySqlSlaves(ec2, spec, mainServers[0]),
                terracottaHosts: mainServers,
                tomcats: mainServers,
                apacheServer: mainServers[0],
                jmeter: mainServers[0]
                )
    }

    def allocateMySqlSlaves(CloudManager ec2, ClusterSpec spec, EC2Server mainServer) {
        if (spec.useHaSlave)
            return ec2.newServersElsewhere(1, spec.slaveDatabaseInstanceType, mainServer, [:]) + ec2.newServers(spec.numberOfSlaves - 1, spec.slaveDatabaseInstanceType)
        else
            return ec2.newServers(spec.numberOfSlaves, spec.slaveDatabaseInstanceType)
    }
}